Hey Magento folks, this article is based on Magento2 1.0.0 beta version. I will be briefly explaining the event observers in Magento2. Developers who have worked on Magento 1.x series are well aware the importance of events-observers in terms of developing custom functionality, and a way to avoid core code modification.
In Magento2 , it is nearly the same concept, just the aesthetics of using it has changed. So lets dive into it without any further ado.
Contrary to Magento 1.x, all event defintions fo into a seperate xml file i.e events.xml
So in your module folder, there could be three events file.
- etc/events.xml
- etc/frontend/events.xml
- etc/adminhtml/events.xml
So as you might have guessed first file is for global scope and then frontend , adminhtml respectively.
So late’s say, i need to observer event, checkout_cart_add_product_complete
i will create an events.xml
* @param \Magento\Framework\Event\Observer $observer
* @return void
*
*/
public function execute(\Magento\Framework\Event\Observer $observer)
{
//execute your code here
}
Okie, so going deep into, how the events are initialize
//file \Magento\Checkout\Controller\Cart\Add.php -113
$this->_eventManager->dispatch(
‘checkout_cart_add_product_complete’,
[‘product’ => $product, ‘request’ => $this->getRequest(), ‘response’ => $this->getResponse()]
);
Where event manager is a object of \Magento\Framework\Event\ManagerInterface
So in same way we could initialize and fire our own custom events.
You can find list of events fired throughout Magento2 here